package com.stgy.lease.web.admin.controller.attr;

import com.stgy.lease.common.redis.RedisPrefixEnum;
import com.stgy.lease.common.result.Result;
import com.stgy.lease.model.domain.LeaseTerm;
import com.stgy.lease.web.admin.service.LeaseTermService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:TermController
 * Package:com.stgy.lease.web.admin.controller
 * Description:
 *
 * @Author:helei
 * @Create:2024/8/30 - 8:40
 */
@Tag(name = "房间租期管理")
@RestController
@RequestMapping("/admin/term")
public class TermController {

    @Autowired
    private LeaseTermService leaseTermService;

    @Autowired
    private RedisTemplate redisTemplate;

    private String termListKey = RedisPrefixEnum.STGY_ADMIN_PREFIX + "term:list";

    //http://localhost:5174/admin/term/deleteById?id=1829322177770438657 DELETE
    @Operation(summary = "根据id删除租期")
    @DeleteMapping("/deleteById")
    public Result<String> deleteById(@RequestParam("id") List<Long> ids) {
        boolean b = leaseTermService.removeByIds(ids);
        if (b) {
            redisTemplate.delete(termListKey);
        }
        return Result.build(b);
    }

    //http://localhost:5174/admin/term/saveOrUpdate POST
    //{"id":"6","unit":"月","monthCount":12}
    @Operation(summary = "新增或者更新租期")
    @PostMapping("/saveOrUpdate")
    public Result<String> saveOrUpdate(@RequestBody LeaseTerm leaseTerm) {
        Boolean b = leaseTermService.saveOrUpdateByStats(leaseTerm);
        if (b) {
            redisTemplate.delete(termListKey);
        }
        return Result.build(b);
    }


    //http://localhost:5174/admin/term/list GET
    @Operation(summary = "查询所有租期")
    @GetMapping("/list")
    public Result<List<LeaseTerm>> list() {
        List<LeaseTerm> list = (List<LeaseTerm>) redisTemplate.opsForValue().get(termListKey);
        if (list == null) {
            list = leaseTermService.list();
            redisTemplate.opsForValue().set(termListKey, list, 1, TimeUnit.DAYS);
        }
        return Result.ok(list);
    }


}
